const { 
  identifyTenant, 
  requireTenant, 
  enforceTenantIsolation 
} = require('../middleware/tenant');
const { 
  authenticate, 
  requireRole, 
  requirePermission,
  requireSelfOrAdmin 
} = require('../middleware/auth');

/**
 * 用户管理路由
 * @param {FastifyInstance} fastify
 * @param {Object} options
 */
async function userRoutes(fastify, options) {
  // 应用中间件
  fastify.addHook('preHandler', identifyTenant);
  fastify.addHook('preHandler', requireTenant);
  fastify.addHook('preHandler', authenticate);
  fastify.addHook('preHandler', enforceTenantIsolation);

  // 获取当前租户的所有用户 (管理员权限)
  fastify.get('/users', {
    preHandler: [requireRole(['admin', 'owner'])],
    schema: {
      tags: ['User Management'],
      summary: 'Get all users in current tenant',
      security: [{ Bearer: [] }],
      querystring: {
        type: 'object',
        properties: {
          page: { type: 'integer', minimum: 1, default: 1 },
          limit: { type: 'integer', minimum: 1, maximum: 100, default: 10 },
          sort: { type: 'string', enum: ['asc', 'desc'], default: 'desc' },
          sortBy: { type: 'string', default: 'createdAt' },
          search: { type: 'string', description: 'Search by name or email' },
          role: { type: 'string', enum: ['owner', 'admin', 'user'] },
          status: { type: 'string', enum: ['active', 'inactive', 'pending'] }
        }
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'array',
              items: {
                type: 'object',
                properties: {
                  _id: { type: 'string' },
                  tenantId: { type: 'string' },
                  email: { type: 'string' },
                  firstName: { type: 'string' },
                  lastName: { type: 'string' },
                  role: { type: 'string' },
                  status: { type: 'string' },
                  lastLoginAt: { type: 'string', format: 'date-time' },
                  createdAt: { type: 'string', format: 'date-time' },
                  updatedAt: { type: 'string', format: 'date-time' }
                }
              }
            },
            meta: {
              type: 'object',
              properties: {
                pagination: {
                  type: 'object',
                  properties: {
                    total: { type: 'integer' },
                    page: { type: 'integer' },
                    limit: { type: 'integer' },
                    totalPages: { type: 'integer' },
                    hasNext: { type: 'boolean' },
                    hasPrev: { type: 'boolean' }
                  }
                }
              }
            }
          }
        }
      }
    }
  }, async (request, reply) => {
    const userController = require('../controllers/userController');
    return await userController.getUsers(request, reply);
  });

  // 获取特定用户信息
  fastify.get('/users/:userId', {
    preHandler: [requireSelfOrAdmin],
    schema: {
      tags: ['User Management'],
      summary: 'Get user by ID',
      security: [{ Bearer: [] }],
      params: {
        type: 'object',
        required: ['userId'],
        properties: {
          userId: { type: 'string', pattern: '^[0-9a-fA-F]{24}$' }
        }
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'object',
              properties: {
                _id: { type: 'string' },
                tenantId: { type: 'string' },
                email: { type: 'string' },
                firstName: { type: 'string' },
                lastName: { type: 'string' },
                role: { type: 'string' },
                status: { type: 'string' },
                profile: { type: 'object' },
                preferences: { type: 'object' },
                lastLoginAt: { type: 'string', format: 'date-time' },
                createdAt: { type: 'string', format: 'date-time' },
                updatedAt: { type: 'string', format: 'date-time' }
              }
            }
          }
        }
      }
    }
  }, async (request, reply) => {
    const userController = require('../controllers/userController');
    return await userController.getUserById(request, reply);
  });

  // 更新用户信息
  fastify.put('/users/:userId', {
    preHandler: [requireSelfOrAdmin],
    schema: {
      tags: ['User Management'],
      summary: 'Update user information',
      security: [{ Bearer: [] }],
      params: {
        type: 'object',
        required: ['userId'],
        properties: {
          userId: { type: 'string', pattern: '^[0-9a-fA-F]{24}$' }
        }
      },
      body: {
        type: 'object',
        properties: {
          firstName: { type: 'string', minLength: 1, maxLength: 50 },
          lastName: { type: 'string', minLength: 1, maxLength: 50 },
          profile: {
            type: 'object',
            properties: {
              avatar: { type: 'string', format: 'uri' },
              bio: { type: 'string', maxLength: 500 },
              phone: { type: 'string' },
              timezone: { type: 'string' },
              language: { type: 'string' }
            }
          },
          preferences: {
            type: 'object',
            properties: {
              theme: { type: 'string', enum: ['light', 'dark', 'auto'] },
              notifications: {
                type: 'object',
                properties: {
                  email: { type: 'boolean' },
                  push: { type: 'boolean' },
                  sms: { type: 'boolean' }
                }
              }
            }
          }
        }
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'object',
              properties: {
                _id: { type: 'string' },
                email: { type: 'string' },
                firstName: { type: 'string' },
                lastName: { type: 'string' },
                profile: { type: 'object' },
                preferences: { type: 'object' },
                updatedAt: { type: 'string', format: 'date-time' }
              }
            }
          }
        }
      }
    }
  }, async (request, reply) => {
    const userController = require('../controllers/userController');
    return await userController.updateUser(request, reply);
  });

  // 更新用户角色 (仅管理员)
  fastify.patch('/users/:userId/role', {
    preHandler: [requireRole(['admin', 'owner'])],
    schema: {
      tags: ['User Management'],
      summary: 'Update user role',
      security: [{ Bearer: [] }],
      params: {
        type: 'object',
        required: ['userId'],
        properties: {
          userId: { type: 'string', pattern: '^[0-9a-fA-F]{24}$' }
        }
      },
      body: {
        type: 'object',
        required: ['role'],
        properties: {
          role: { type: 'string', enum: ['user', 'admin'] }
        }
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'object',
              properties: {
                _id: { type: 'string' },
                email: { type: 'string' },
                role: { type: 'string' },
                updatedAt: { type: 'string', format: 'date-time' }
              }
            }
          }
        }
      }
    }
  }, async (request, reply) => {
    const userController = require('../controllers/userController');
    return await userController.updateUserRole(request, reply);
  });

  // 更新用户状态 (仅管理员)
  fastify.patch('/users/:userId/status', {
    preHandler: [requireRole(['admin', 'owner'])],
    schema: {
      tags: ['User Management'],
      summary: 'Update user status',
      security: [{ Bearer: [] }],
      params: {
        type: 'object',
        required: ['userId'],
        properties: {
          userId: { type: 'string', pattern: '^[0-9a-fA-F]{24}$' }
        }
      },
      body: {
        type: 'object',
        required: ['status'],
        properties: {
          status: { type: 'string', enum: ['active', 'inactive', 'suspended'] },
          reason: { type: 'string', maxLength: 200 }
        }
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'object',
              properties: {
                _id: { type: 'string' },
                email: { type: 'string' },
                status: { type: 'string' },
                updatedAt: { type: 'string', format: 'date-time' }
              }
            }
          }
        }
      }
    }
  }, async (request, reply) => {
    const userController = require('../controllers/userController');
    return await userController.updateUserStatus(request, reply);
  });

  // 删除用户 (仅管理员)
  fastify.delete('/users/:userId', {
    preHandler: [requireRole(['admin', 'owner'])],
    schema: {
      tags: ['User Management'],
      summary: 'Delete user',
      security: [{ Bearer: [] }],
      params: {
        type: 'object',
        required: ['userId'],
        properties: {
          userId: { type: 'string', pattern: '^[0-9a-fA-F]{24}$' }
        }
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' }
          }
        }
      }
    }
  }, async (request, reply) => {
    const userController = require('../controllers/userController');
    return await userController.deleteUser(request, reply);
  });

  // 邀请用户
  fastify.post('/users/invite', {
    preHandler: [requireRole(['admin', 'owner'])],
    schema: {
      tags: ['User Management'],
      summary: 'Invite user to tenant',
      security: [{ Bearer: [] }],
      body: {
        type: 'object',
        required: ['email', 'role'],
        properties: {
          email: { type: 'string', format: 'email' },
          role: { type: 'string', enum: ['user', 'admin'] },
          firstName: { type: 'string', minLength: 1, maxLength: 50 },
          lastName: { type: 'string', minLength: 1, maxLength: 50 },
          message: { type: 'string', maxLength: 500 }
        }
      },
      response: {
        201: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'object',
              properties: {
                inviteId: { type: 'string' },
                email: { type: 'string' },
                role: { type: 'string' },
                expiresAt: { type: 'string', format: 'date-time' }
              }
            }
          }
        }
      }
    }
  }, async (request, reply) => {
    const userController = require('../controllers/userController');
    return await userController.inviteUser(request, reply);
  });

  // 获取用户活动日志
  fastify.get('/users/:userId/activities', {
    preHandler: [requireSelfOrAdmin],
    schema: {
      tags: ['User Management'],
      summary: 'Get user activity logs',
      security: [{ Bearer: [] }],
      params: {
        type: 'object',
        required: ['userId'],
        properties: {
          userId: { type: 'string', pattern: '^[0-9a-fA-F]{24}$' }
        }
      },
      querystring: {
        type: 'object',
        properties: {
          page: { type: 'integer', minimum: 1, default: 1 },
          limit: { type: 'integer', minimum: 1, maximum: 100, default: 20 },
          type: { type: 'string' },
          startDate: { type: 'string', format: 'date' },
          endDate: { type: 'string', format: 'date' }
        }
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'array',
              items: {
                type: 'object',
                properties: {
                  _id: { type: 'string' },
                  type: { type: 'string' },
                  description: { type: 'string' },
                  metadata: { type: 'object' },
                  ipAddress: { type: 'string' },
                  userAgent: { type: 'string' },
                  createdAt: { type: 'string', format: 'date-time' }
                }
              }
            },
            meta: {
              type: 'object',
              properties: {
                pagination: {
                  type: 'object',
                  properties: {
                    total: { type: 'integer' },
                    page: { type: 'integer' },
                    limit: { type: 'integer' },
                    totalPages: { type: 'integer' }
                  }
                }
              }
            }
          }
        }
      }
    }
  }, async (request, reply) => {
    const userController = require('../controllers/userController');
    return await userController.getUserActivities(request, reply);
  });
}

module.exports = userRoutes;